import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router'
import routes from './router'

// Vue.config.productionTip = false

let instance = null
let router = null

function render (props) {
  router = new VueRouter({
    base: window.__POWERED_BY_QIANKUN__ ? '/vue' : '/',
    mode: 'history',
    routes
  })
  instance = new Vue({
    router,
    render: h => h(App)
  }).$mount('#vue_app') // 挂载到自己的html 中，基座会拿到这个挂载后的html 将其插入进去
}

// 使用 webpack 运行时 publicPath 配置
if (window.__POWERED_BY_QIANKUN__) {
  __webpack_public_path__ = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__
}

// 独立运行微应用
if (!window.__POWERED_BY_QIANKUN__) {
  render()
}


function getGlobalState(props) {
  props.onGlobalStateChange &&
    props.onGlobalStateChange(
      (value, prev) => {
        console.log(`%c [vue 子应用 onGlobalStateChange]: ${props.name} `, 'font-size: 20px; color: purple', value, prev)
      },
      true,
    )
  Vue.prototype.$globalStateChange = props.onGlobalStateChange
  Vue.prototype.$setGlobalState = props.setGlobalState
}


// 定义子组件的协议
export async function bootstrap (props) {
  console.log('vue 子应用 bootstrap', props)
}
export async function mount (props) {
  console.log('vue 子应用 mount', props)
  getGlobalState(props)
  render(props)
}
export async function unmount (props) {
  console.log('vue 子应用 unmount', props)
  instance.$destroy()
  router = null
  instance = null
}
